package org.ezplatform.office.questionnaire.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.org.OrgApiService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.component.permission.service.CmpApplyScopeService;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.office.questionnaire.dao.QuestionnaireDao;
import org.ezplatform.office.questionnaire.dao.QusetionnaireAnswerStatusDao;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireTopic;
import org.ezplatform.office.questionnaire.entity.QusetionnaireAnswerStatus;
import org.ezplatform.office.questionnaire.util.SendMsgUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * <br> 问卷接口类
 * <br> 创建时间 2017-11-23
 * @author wujs
 * @version 1.0
 * 
*/

@Service("questionnaireService")
@Transactional
public class QuestionnaireService extends BaseService<Questionnaire,String>{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireService.class);
	
	@Autowired
	@Qualifier("questionnaireDao")
	private QuestionnaireDao questionnaireDao;
	
	@Autowired
	@Qualifier("qusetionnaireAnswerStatusDao")
	private QusetionnaireAnswerStatusDao answerStatusDao;
	@Lazy
	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private PopUserScopeUtilService popScopeService;
	
//	@Autowired
//	private DictDetailApiService dictApiService;
	@Lazy
	@Autowired
	private QuestionnaireTopicService topicService;
	
	@Autowired
	private UserApiService userApiService;
	
	@Autowired
	private OrgApiService orgApiService;

//	@Autowired
//	private QuestionnaireAnswerStatusService answerStatusService;

//	@Autowired
//	private DingMessageUtil dingMessageUtil;
	
	@Autowired
	private SendMsgUtils sendMsgUtils;
	@Lazy
	@Autowired
	private CmpApplyScopeService cmpApplyScopeService;

	private QusetionnaireAnswerStatus status;
	
	@Override
	protected JpaBaseDao<Questionnaire, String> getEntityDao() {
		return questionnaireDao;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String,Object> getWindowMsg(String userId,String corpId,String token,HttpServletRequest request) {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("corpId", corpId);
		paramMap.put("createdBy", userId);
		StringBuffer sb=new StringBuffer();
		sb.append("SELECT oq.id, oqas.id status_id, oq.name, oq.type, oq.start_date AS startDate, oq.end_date AS endDate, oq.status, oqas.status answerStatus,oq.createdDate,oq.publish,oq.close_date as closeDate,oq.no_limit as noLimitSet,oqas.answer_num as answerNum,oqas.grade,oq.pass_score as passScore,oq.answer_num as answerNumSet ");
		sb.append(" FROM oa_questionnaire oq ");
		sb.append(" LEFT JOIN (SELECT id,status,questionnaire_id,answer_num,grade from  oa_qusetionnaire_answer_status where createdBy =:createdBy) oqas ON oqas.questionnaire_id = oq.ID  WHERE oq.corp_id = :corpId ");
		sb.append(" and oq.publish = " + Questionnaire.PublishEnum.PUBLISH.getCode());
		sb.append(" and oq.type = 'questionnaireExam'");
		sb.append(" and (oqas.status ='0' or oqas.status ='1' or oqas.status is null)");
		String scopeSql = this.cmpApplyScopeService.getInScopeDataSql(userId, "oa_questionnaire_scope", "oa_questionnaire", "questionnaire_scope", "oq", paramMap);
		sb.append(" and "+scopeSql);
		
		List<Map> myQues=this.findByListNativeQuery(sb.toString(), "oq.createdDate desc ",paramMap);
		Map quesInfoRe=new HashMap<>();
		if(myQues!=null && myQues.size()>0) {
			List<Map> ques=new ArrayList<>();
			for(Map ele:myQues) {
				if("1".equals(ele.get("answerStatus"))||ele.get("answerStatus")==null) {
					//ques.add(ele);
					if(canToAnswer(ele)) {
						ques.add(ele);
					}
				}
			}
			if(ques.size()>0 ) {
				Map quesInfo=new HashMap<>();
				quesInfo=ques.get(0);
				List<QuestionnaireTopic> topics=topicService.getDingTopicOPtionInfo((String)quesInfo.get("id"), userId, "", token);
				Map<String,Object> topicType=new HashMap<>();
				for(QuestionnaireTopic topic:topics) {
					if(!"paging".equals(topic.getTopicType())&&!"illustrate".equals(topic.getTopicType())) {
						Integer tN=0;
						//单选
						if("sinselect".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("sinselect");
							if(tN!=null) {
								topicType.put("sinselect", ++tN);
							}else {
								topicType.put("sinselect", 1);
								topicType.put("sinselectName", "考试单选");
							}
						}
						//多选
						else if("multiselect".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("multiselect");
							if(tN!=null) {
								topicType.put("multiselect", ++tN);
							}else {
								topicType.put("multiselect", 1);
								topicType.put("multiselectName", "考试多选");
							}
						}
						//判断
						else if("trueOrFalse".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("trueOrFalse");
							if(tN!=null) {
								topicType.put("trueOrFalse", ++tN);
							}else {
								topicType.put("trueOrFalse", 1);
								topicType.put("trueOrFalseName", "考试判断");
							} 
						}
						//单项填空
						else if("answer".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("answer");
							if(tN!=null) {
								topicType.put("answer", ++tN);
							}else {
								topicType.put("answer", 1);
								topicType.put("answerName",  "单项填空");
							}
						}
						//多项填空
						else if("fillInBlanks".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("fillInBlanks");
							if(tN!=null) {
								topicType.put("fillInBlanks", ++tN);
							}else {
								topicType.put("fillInBlanks", 1);
								topicType.put("fillInBlanksName", "多项填空");
							}
						}
						//考试简答
						else if("shortAnswer".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("shortAnswer");
							if(tN!=null) {
								topicType.put("shortAnswer", ++tN);
							}else {
								topicType.put("shortAnswer", 1);
								topicType.put("shortAnswerName", "考试简单");
							}
						}
						//考试文件
						else if("field".equals(topic.getTopicType())) {
							tN=(Integer)topicType.get("field");
							if(tN!=null) {
								topicType.put("field", ++tN);
							}else {
								topicType.put("field", 1);
								topicType.put("fieldName", "考试文件");
							}
						}
					}
				}
				quesInfoRe.put("answerUrl", "modules/questionnaire/questionnaire_answer.html?quesitionnaireId="+quesInfo.get("id"));
				quesInfoRe.put("quesName", StringUtils.null2String(quesInfo.get("name")));
				quesInfoRe.put("topicTypeNum", topicType);
				Date startDate=(Date)quesInfo.get("startDate");
				Date endDate=(Date)quesInfo.get("endDate");
				Date closeDate=(Date)quesInfo.get("closeDate");
				quesInfoRe.put("passScore", StringUtils.null2String(quesInfo.get("passScore")));
				if(startDate!=null && endDate!=null) {
					//分钟
					long intervalTime=(endDate.getTime()-startDate.getTime())/60000;
					quesInfoRe.put("intervalTime", intervalTime+"");
				}
				if(closeDate!=null) {
					//天
					long deadlineTime=(closeDate.getTime()-new Date().getTime())/(24*3600*1000);
					quesInfoRe.put("deadlineTime", deadlineTime+"");
				}
			}
		}
		
		return quesInfoRe;
	}
	
	/**
	 * 判断问卷名称是否相同
	 * @param id 问卷ID
	 * @param name 问卷名称
	 * @param corpId 单位ID
	 * @return 相同返回true、不同返回false
	 */
	public boolean checkName(String id,String name,String corpId){
		boolean flag= false;
		Questionnaire oq = questionnaireDao.getQuestionnaireByName(name,corpId);
		if(oq !=null){
			if(!"".equals(StringUtils.null2String(id))){
				if(!id.equals(oq.getId())){
					return true;
				}
			}else{
				return true;
			}
		}
		return flag;
	}
	
	/**
	 * 更新问卷状态：当前日期大于开始日期时，将未开启状态改为开启状态；当前日期大于结束时间，将开启状态改为关闭状态
	 * @return 更新成功返回true
	 */
	public boolean updateQuestionnaireStatus(){
		questionnaireDao.updateSetOpenStatus();
		questionnaireDao.updateSetCloseStatus();
		return true;
	}
	
	/**
	 * 获取问卷信息
	 * @param userId 用户id
	 * @param corpId 单位ID
	 * @param token 系统参数：TOKEN
	 * @return 问卷实体集合
	 */
	public List<Questionnaire> getQuesInfoByUserId(String userId,String corpId,String token){
//		List<String> userList = new ArrayList<String>();
//		userList.add(userId);
//		List<String> listUos =orgApiService.getOrgIdsByUserIds(userId,corpId,"","2",token);
//		if(listUos == null || listUos.size()==0){
//			userList.addAll(listUos);
//		}
//		List<String> list = popScopeService.getFieldDataValue("oa_questionnaire_scope", userList, "oa_questionnaire", "questionnaire_scope");
//		if(list == null || list.size()==0){
//			return null;
//		}
		List<String> list =orgApiService.getOrgIdsByUserIds(userId,corpId,"","2",token);
		if(list==null) {
			return null;
		}
		list.add(userId);
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("corpId", corpId);
		List<String> scopeList = popScopeService.getFieldDataValue("oa_questionnaire_scope", list, "oa_questionnaire", "questionnaire_scope");
		if(scopeList == null || scopeList.size()==0){
			scopeList.add("-999");
		}
		if(list == null || list.size()==0){
			return null;
		}
		//获得开启状态下有当前答题范围中包含自己的id集合
		List<String> quesIdsList = questionnaireDao.getQuestionIdsByQuesScope(scopeList,corpId,Questionnaire.PublishEnum.PUBLISH.getCode());
		//默认所有人的问卷id集合
		List<String> defaultList = questionnaireDao.getQuestionIdsByQuesScopeIsNull(corpId, Questionnaire.PublishEnum.PUBLISH.getCode());
		if(CollectionUtils.isNotEmpty(defaultList)) quesIdsList.addAll(defaultList);
		List<String> answerQuesIds = null;
		List<Questionnaire> quesList = null;
		if(quesIdsList != null && quesIdsList.size()>0) {
			//未答题的题目id集合
			answerQuesIds = answerStatusDao.getQuesIdStatus("0",quesIdsList,userId);
			List<String> havStatusQuesId = answerStatusDao.getQuesIdStatus("1",quesIdsList,userId);
			if(havStatusQuesId==null) {
				havStatusQuesId=new ArrayList(0);
			}
			//不应该包含已评阅的题目
			List<String> havStatusQuesId2 = answerStatusDao.getQuesIdStatus("4",quesIdsList,userId);
			if(havStatusQuesId2==null) {
				havStatusQuesId2=new ArrayList(0);
			}
			havStatusQuesId.addAll(havStatusQuesId2);
			if(havStatusQuesId.size()>0){
				for(int i=0;i<quesIdsList.size();i++){
					if(!havStatusQuesId.contains(quesIdsList.get(i))){
						answerQuesIds.add(quesIdsList.get(i));
					}
				}
			}else{
				answerQuesIds.addAll(quesIdsList);
			}
			if(answerQuesIds !=null && answerQuesIds.size()>0) {
				quesList = questionnaireDao.getQuestionnaireList(answerQuesIds);
			}
			
		}
		//判断问卷状态
//		if(false && CollectionUtils.isNotEmpty(quesList)){
//			Date nowTime = new Date();
//			Date startDate;
//			Date endDate;
//			for (Questionnaire m : quesList ) {
//				startDate = m.getStartDate();
//				endDate = m.getEndDate();
//				int topicNum = topicService.getQuesTopic(m.getId());
//				if(startDate.getTime() <= nowTime.getTime()
//						&& endDate.getTime() > nowTime.getTime()
//						&& StringUtils.equals(Questionnaire.StatusEnum.NOOPEN.getCode(),m.getStatus())){
//					if(topicNum > 0) {
//						m.setStatus(Questionnaire.StatusEnum.OPEN.getCode());
//					}
//				}
//				if(endDate.getTime() <= nowTime.getTime()
//						&& !StringUtils.equals(Questionnaire.StatusEnum.CLOSE.getCode(),m.getStatus())){
//					if(topicNum > 0) {
//						m.setStatus(Questionnaire.StatusEnum.CLOSE.getCode());
//					}
//				}
//			}
//		}
		return quesList;
	}
	
	/**
	 * 门户获取问卷信息
	 * @param list 问卷实体集合
	 * @param token 系统参数：TOKEN
	 * @param corpId 单位ID
	 * @param showNumber 显示条数
	 * @return 问卷信息:[{"name":"问卷名称","id":"问卷id","type":"问卷类型：调查、投票","endDate":"结束时间"},……]
	 */
	public List<Map<String,Object>> getQuesPageInfo(List<Questionnaire> list,String token,String corpId,int showNumber){
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
//		List<Map<String,Object>> dictList = dictApiService.getDictDetailByCode("questionnaireType",corpId,token);
		Map<Object,Object> codeMap = new HashMap<Object,Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//		for(int i=0;i<dictList.size();i++){
//			codeMap.put(dictList.get(i).get("code"), dictList.get(i).get("name"));
//		}
		codeMap.put("questionnaireVote", "投票");
		codeMap.put("questionnaireSurvey", "调查");
		codeMap.put("questionnaireExam", "考试");
		Questionnaire ques ;
		Map<String,Object> map ;
		for(int i = 0 ; i < list.size() && i < showNumber ; i ++){
			ques = list.get(i);
			if(!(ques.getPublish() == Questionnaire.PublishEnum.PUBLISH.getCode())){
				showNumber ++;
				continue;
			}
			map = new HashMap<String,Object>();
			map.put("name", ques.getName());
			map.put("id", ques.getId());
			map.put("type", codeMap.get(ques.getType()));
			if(ques.getEndDate()!=null) {
				map.put("endDate", sdf.format(ques.getEndDate()));
			}
			if(ques.getCloseDate()!=null) {
				map.put("closeDate", sdf.format(ques.getCloseDate()));
			}
			map.put("createdDate", sdf.format(ques.getCreatedDate()));
			Map userMap = userApiService.getUser(ques.getCreatedBy(), corpId, "", token);
			if(userMap!=null) {
				map.put("createdByName", userMap.get("userName"));
			}else {
				map.put("createdByName", "");
			}
			mapList.add(map);
		}
		return mapList;
	}
	
	/**
	 * 根据问卷ID获取问卷适用范围
	 * @param quesIdList 问卷id
	 * @return 问卷适用范围ID集合
	 */
	public List<String> getQuesScopeById(List<String> quesIdList){
		List<Questionnaire> queslist = questionnaireDao.getQuestionnaireList(quesIdList);
		List<String> list = new ArrayList<String>();
		for(int i=0;i<queslist.size();i++){
			Questionnaire ques =queslist.get(i);
			list.add(ques.getQuestionnaireScope());
		}
		return list;
	}
	
	/**
	 * 根据问卷ID获取问卷答卷范围
	 * @param quesIdList 问卷id集合
	 * @return 问卷答卷范围id集合
	 */
	public List<String> getAnswerScopeById(List<String> quesIdList){
		List<Questionnaire> queslist = questionnaireDao.getQuestionnaireList(quesIdList);
		List<String> list = new ArrayList<String>();
		for(int i=0;i<queslist.size();i++){
			Questionnaire ques =queslist.get(i);
			list.add(ques.getAnswerScope());
		}
		return list;
	}


	/**
	 * 根据id 更新问卷状态
	 * @param id
	 * @return   0:关闭   1：开启    2：未开启     -1：没有找到问卷
	 */
	public int updateQuStatus(String id,String userId, String corpId, String token, HttpServletRequest request){
//		Questionnaire questionnaire = this.findOne(id);
//		if(questionnaire != null){
//			Date startTime = questionnaire.getStartDate();
//			Date endTime = questionnaire.getEndDate();
//			Long startMis = startTime.getTime();
//			Long endMis = endTime.getTime();
//			Long nowMis = new Date().getTime();
//			int topicNum = topicService.getQuesTopic(id);
//			//当前时间在 开始时间与结束时间之间，状态为未开启状态，且有题目  开启问卷
//			if(startMis <= nowMis && endMis > nowMis
//					&& StringUtils.equals(Questionnaire.StatusEnum.NOOPEN.getCode(),questionnaire.getStatus())){
//				if(topicNum != 0) {
//					//开启问卷的时候 问卷没有推送 推送
//					if(Questionnaire.SendStatusEnum.NOSEND.getCode() == questionnaire.getSendStatus()){
//						if(StringUtils.isNotBlank(token)){
//							sendThreadQues(id,userId,corpId,token,request);
//							setQuesSendY(id);
//						}
//					}
//					questionnaireDao.updateQuStatus(id,Questionnaire.StatusEnum.OPEN.getCode());
//					return 1;  //开启
//				}
//			}
//			//当前时间再 结束时间之后，状态不是关闭状态的问卷,且有题目，关闭问卷
//			if(endMis <= nowMis
//					&& !StringUtils.equals(Questionnaire.StatusEnum.CLOSE.getCode(),questionnaire.getStatus())){
//				if(topicNum != 0) {
//					questionnaireDao.updateQuStatus(id, Questionnaire.StatusEnum.CLOSE.getCode());
//					//修改问卷 草稿的状态
//					answerStatusService.updateStatusToSubmit(id);
//					//问卷关闭  问卷推送状态改为未推送状态
//					setQuesSendN(id);
//					return 0;		//关闭
//				}
//			}
//			return Integer.parseInt(questionnaire.getStatus());
//		}
		return -1;
	}


	/**
	 * 线程 推送
	 * @param quesId
	 * @param corpId
	 * @param token
	 * @param request
	 */
	public void sendThreadQues(String quesId,String userId,String corpId,String token,HttpServletRequest request){
		String url = GlobalConstant.getAppFlexOfficeServerUrl();//getFlexOfficePath(request)
		sendQues(quesId,userId,corpId,token,url,request);
	}

	/**
	 * 发送 推送
	 * @param quesId
	 * @param request 
	 */
	public void sendQues(String quesId,String userId,String corpId,String token,String url, HttpServletRequest request){
		Questionnaire questionnaire = this.findOne(quesId);
		String remindTarget=questionnaire.getRemindTarget();
		if(questionnaire.getSendStatus() == Questionnaire.SendStatusEnum.SEND.getCode()){
			return;
		}
		//所有需要推送的人的userid
		List<String> userIdList = new ArrayList<>();
		if(StringUtils.isNotBlank(questionnaire.getQuestionnaireScope())) {
			List<Map> scopeList = getQuesScope(quesId);
			if(CollectionUtils.isNotEmpty(scopeList)) {
				for(Map scope : scopeList){
					//选择类型
					String scopeType = StringUtils.null2String(scope.get("scopeType"));
					if(StringUtils.equals(scopeType,"user")){
						userIdList.add(StringUtils.null2String(scope.get("scopeValue")));
					}else if(StringUtils.equals(scopeType,"org")){
						List<String> l =
								userApiService.getUserIdsByOrgId(
										StringUtils.null2String(scope.get("scopeValue")),
										"","1",corpId,token);
						userIdList.addAll(l);
					}
				}
			}
		}else {
			List<Map> list = questionnaireService.getAllUser(corpId);
			if(CollectionUtils.isNotEmpty(list)) {
				for(Map user : list) {
					userIdList.add(StringUtils.null2String(user.get("id")));
				}
			}
		}
		//查询已经提交的人id（key是id）
		Map<String,String> map1 = getQuesSubmitUserIds(quesId,userIdList);
		//遍历，剔除已经提交的人
		List<String> userLists = new ArrayList<>();
		for(String value : userIdList){
			if(map1.get(value) == null){
				userLists.add(value);
			}
		}

		Map<String,Object> map = new HashMap<>();
		//问卷名称
		map.put("quesName",questionnaire.getName());
		//问卷开始时间
		map.put("quesStarTime",questionnaire.getStartDate());
		//问卷结束时间
		map.put("closeDate",questionnaire.getCloseDate());
		map.put("quesId",quesId);
		
		StringBuffer userIdsBuilder = new StringBuffer();
		StringBuffer jsonIdsBuilder = new StringBuffer("[");
		for(String id : userLists){
			if(!userIdsBuilder.toString().contains(id)) {
				userIdsBuilder.append(id).append(",");
				jsonIdsBuilder.append("{\"10\":\"").append(id).append("\"},");
			}
		}
		String userIds = userIdsBuilder.toString();
		String jsonIds = jsonIdsBuilder.toString();
		if(userIds.length() > 1 && userIds.charAt(userIds.length() - 1) == ',') {
			userIds = userIds.substring(0, userIds.length() - 1);
			jsonIds = jsonIds.substring(0, jsonIds.length() - 1);
		}
		jsonIds += "]";
		map.put("userIds",userIds);
		map.put("type", SendMsgUtils.NEWQUESSTATUS);
		map.put("url",url);
		map.put("remindTarget", remindTarget);
		LOGGER.debug("zhaozy: "+remindTarget);
		LOGGER.error("zhaozy: "+remindTarget);
		if(!StringUtils.isEmpty(remindTarget)) {
			sendMsgUtils.sendMsgToApp(corpId, token, map, request, userId);
		}
		Map<String,String> paramMap = new HashMap<>();
		paramMap.put("userId",userId);
		paramMap.put("corpId",corpId);
		paramMap.put("token",token);
		paramMap.put("msgTitle",SendMsgUtils.NEWQUES_FOR_HOA+questionnaire.getName());
		paramMap.put("dataId", UuidUtils.UUID());
		paramMap.put("msgContent",SendMsgUtils.NEWQUES_FOR_HOA+questionnaire.getName());
		paramMap.put("url",SendMsgUtils.QUES_ANSWER_URL);
		paramMap.put("quesitionnaireId",quesId);
		paramMap.put("msgReceiver", jsonIds);
		sendMsgUtils.sendMsgToOffice(paramMap);
	}


	/**
	 * 发送 推送  定时任务
	 * @param quesId
	 */
	public void sendQuesForJob(String quesId,String corpId,String token,HttpServletRequest request){
		GlobalConstant globalConstant = new GlobalConstant();
		String url = globalConstant.getFlexOfficePath(request);

		Questionnaire questionnaire = questionnaireService.findOne(quesId);
		List<String> userValue = new ArrayList<>();
		if(StringUtils.isNotBlank(questionnaire.getQuestionnaireScope())) {
			List<Map> scopeList = getQuesScope(quesId);
			if(CollectionUtils.isNotEmpty(scopeList)) {
				List<String> orgValue = new ArrayList<>();
				String scopeType ;
				String scopeValue;
				for(Map scope : scopeList){
					scopeType = StringUtils.null2String(scope.get("scopeType"));
					scopeValue = StringUtils.null2String(scope.get("scopeValue"));
					if(StringUtils.equals("user",scopeType)){
						userValue.add(scopeValue);
					}
					if(StringUtils.equals("org",scopeType)){
						orgValue.add(scopeValue);
					}
				}
				List<String> list;
				for(String orgId : orgValue){
				    list = userApiService.getUserIdsByOrgId(orgId,"","1",corpId,token);
				    if(CollectionUtils.isNotEmpty(list)){
						userValue.addAll(list);
					}
				}
			}
		}else {
			List<Map> list = questionnaireService.getAllUser(corpId);
			if(CollectionUtils.isNotEmpty(list)) {
				for(Map user : list) {
					userValue.add(StringUtils.null2String(user.get("id")));
				}
			}
		}
		
		//查询已经提交的人id（key是id）
		Map<String,String> map1 = getQuesSubmitUserIds(quesId,userValue);

		//遍历，剔除已经提交的人
		List<String> userList = new ArrayList<>();
		for(String value : userValue){
		    if(map1.get(value) == null){
				userList.add(value);
			}
		}

		//人员id
		List<String> userIdList = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(userList)){
			StringBuffer sql1 = new StringBuffer();
			sql1.append("select dd_uid from sys_user where id in (:userList) ");
//			Query query1 = super.getEntityManager().createNativeQuery(sql1.toString()).setParameter(1, userList);
//			List<Object> result1 = query1.getResultList();
			Map paramMap = new HashMap();
			paramMap.put("userList", userList);
			List<Map> result1 = super.findByListNativeQuery(sql1.toString(), "",paramMap);
			if(CollectionUtils.isNotEmpty(result1)){
				for(Object re : result1){
					userIdList.add(StringUtils.null2String(re));
				}
			}
		}

		//部门
//		if(CollectionUtils.isNotEmpty(orgValue)){
//			String oIds = "";
//			StringBuffer sql2 = new StringBuffer();
//			sql2.append("select dd_uid from sys_org where id in (?1) ");
//			Query query2 = super.getEntityManager().createNativeQuery(sql2.toString()).setParameter(1, orgValue);
//			List<Object> result2 = query2.getResultList();
//			if(CollectionUtils.isNotEmpty(result2)){
//				for(Object re : result2){
//					orgIdList.add(StringUtils.null2String(re));
//				}
//			}
//		}

		//更新问卷状态  更新成已经推送状态
		setQuesSendY(quesId);
		Map<String,Object> map = new HashMap<>();
		//问卷名称
		map.put("quesName",questionnaire.getName());
		//问卷开始时间
		map.put("quesStarTime",questionnaire.getStartDate());
		//问卷结束时间
		map.put("closeDate",questionnaire.getCloseDate());
		map.put("quesId",quesId);
		
		StringBuffer userIdsBuilder = new StringBuffer();
		StringBuffer jsonIdsBuilder = new StringBuffer("[");
		for(String id : userIdList){
			if(!userIdsBuilder.toString().contains(id)) {
				userIdsBuilder.append(id).append(",");
				jsonIdsBuilder.append("{\"10\":\"").append(id).append("\"},");
			}
		}
		String userIds = userIdsBuilder.toString();
		String jsonIds = jsonIdsBuilder.toString();
		if(userIds.length() > 1 && userIds.charAt(userIds.length() - 1) == ',') {
			userIds = userIds.substring(0, userIds.length() - 1);
			jsonIds = jsonIds.substring(0, jsonIds.length() - 1);
		}
		jsonIds += "]";
		map.put("userIds",userIds);
		map.put("type", SendMsgUtils.NEWQUESSTATUS);
		map.put("url",url);
		sendMsgUtils.sendMsgToApp(corpId, token, map, request, "1");
		
		Map<String,String> paramMap = new HashMap<>();
		paramMap.put("userId","1");
		paramMap.put("corpId",corpId);
		paramMap.put("token",token);
		paramMap.put("msgTitle",SendMsgUtils.NEWQUES_FOR_HOA+questionnaire.getName());
		String dataId = SendMsgUtils.NEWQUESSTATUS+quesId;
		paramMap.put("dataId",dataId.substring(0,dataId.length()-1));
		paramMap.put("msgContent",SendMsgUtils.NEWQUES_FOR_HOA+questionnaire.getName());
		paramMap.put("url",SendMsgUtils.QUES_ANSWER_URL);
		paramMap.put("quesitionnaireId",quesId);

		paramMap.put("msgReceiver", jsonIds);
		sendMsgUtils.sendMsgToOffice(paramMap);

	}


	/**
	 * 根据问卷id 用户id  查询已经提交的用户
	 * @param quesId
	 * @param userIds
	 * @return
	 */
	@SuppressWarnings({"unchecked","rawtypes"})
	private Map<String,String> getQuesSubmitUserIds(String quesId,List<String> userIds){
		StringBuffer sql = new StringBuffer();
		if(CollectionUtils.isEmpty(userIds)){
			userIds.add("-9999");
		}
		sql.append(" SELECT createdBy FROM oa_qusetionnaire_answer_status WHERE questionnaire_id = :quesId AND ${userIds} AND STATUS = 1");
//		Query query = this.getEntityManager().createNativeQuery(sql.toString())
//				.setParameter("quesId", quesId)
//				.setParameter("userIds",userIds);
//		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//		List<Map> r = query.getResultList();
		Map paramMap = new HashMap();
		paramMap.put("quesId", quesId);
		
		StringBuffer sb=new StringBuffer();
		int n=userIds.size()/1000;
		int re=userIds.size()%1000;
		if(n==0) {
			sb.append(" or createdBy IN (:userIds)");
			paramMap.put("userIds", userIds.subList(0, userIds.size()));
		}else {
			for(int start=0,i=0;i<n;start+=1000,i++) {
				sb.append(" or createdBy IN (:userIds"+i+")");
				paramMap.put("userIds"+i, userIds.subList(start, start+1000));
				if(i+1==n && re>0) {
					sb.append(" or createdBy IN (:userIds"+(i+1)+")");
					paramMap.put("userIds"+(i+1), userIds.subList(start+1000,userIds.size()));
				}
			}
		}
		String str="(";
		if(sb.length()>0) {
			str+=sb.substring(3);
		}else str=" 1=1 ";
		str+=")";
		str=sql.toString().replace("${userIds}", str);
		LOGGER.info("zhaozy:"+str);
		
		//由于当不设置考试范围时，默认所有用户，数据量庞大所以，分次查询加载到缓存;弃用str
		List<Map> r =new ArrayList();
		Iterator inter=paramMap.entrySet().iterator();
		while(inter.hasNext()) {
			String sqlQuery=" SELECT createdBy FROM oa_qusetionnaire_answer_status WHERE questionnaire_id = :quesId AND createdBy IN (:userIds) AND STATUS = 1";
			Map.Entry<String,Object> entry=(Map.Entry<String,Object>)inter.next();
			if(!entry.getKey().equals("quesId")) {
				Map param = new HashMap();
				param.put("quesId", quesId);
				List list=(List)entry.getValue();
				param.put("userIds", list);
				List<Map> temp= super.findByListNativeQuery(sqlQuery, "",param);
				if(temp!=null) {
					r.addAll(temp);
				}
			}
		}
		LOGGER.debug("zhaozy:r");
		Map<String,String> map = new HashMap<>();
		for(Map cr : r){
		    map.put(StringUtils.null2String(cr.get("createdBy")),"");
		}
//		if(CollectionUtils.isEmpty(userIds)){
//			String userId = userIds.get(0);
//			userIds.remove(userId);
//		}
		return map;
	}

	
	
/*==================================================钉钉方法================================================================*/	
	
	public List<Map> getQuesList(String corpId, String userId, String quesType,
			String page, String pageSize,String search,String quespublish,String startDate,String endDate) {
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
//		StringBuffer sql = new StringBuffer("SELECT oq.id, oq.name, oq.type as type, oq.start_date AS startDate, oq.end_date AS endDate, oq.status,t.quesId,s.user_name as createdByName FROM oa_questionnaire oq LEFT JOIN (select oqa.questionnaire_id quesId from oa_questionnaire_answer oqa GROUP BY questionnaire_id) t on t.quesId=oq.ID left join sys_user s on s.id=oq.createdBy WHERE oq.corp_id = :corpId");
		StringBuffer sql = new StringBuffer("SELECT oq.id,oq.name,oq.type as type,oq.publish,oq.createdDate,t.quesId "
				+" FROM oa_questionnaire oq LEFT JOIN "
				+" ( SELECT oqa.questionnaire_id quesId FROM oa_questionnaire_answer oqa GROUP BY questionnaire_id ) "
				+" t ON t.quesId = oq.ID WHERE oq.corp_id = :corpId ");
		if(StringUtils.isNotBlank(quesType)){
			sql.append(" and oq.type = '"+quesType + "'");
		}
		if(StringUtils.isNotBlank(quespublish)){
			sql.append(" and oq.publish = " + quespublish);
		}
		if(StringUtils.isNotBlank(startDate)){
			sql.append(" and fn_date_format(oq.createdDate,'yyyy-MM-dd') >= '" + startDate + "'");
		}
		if(StringUtils.isNotBlank(endDate)){
			sql.append(" and fn_date_format(oq.createdDate,'yyyy-MM-dd') <= '" + endDate + "'");
		}
		if(StringUtils.isNotBlank(userId)){
			sql.append(" and oq.createdBy = '"+userId+"'");
		}
//		else{
//			if(type.equals("0")){//所有
//				sql.append("");
//			}else if(type.equals("1")){ //待答
//				sql.append(" and oq.status != '0' ");
//			}else if(type.equals("2")){// 关闭
//				sql.append(" and oq.status == '0' ");
//			}
//		}
		if(StringUtils.isNotBlank(search)){
			search = search.replaceAll("_","\\\\_");
			sql.append(" and oq.name like '%" + search + "%'" );
		}
		sql.append(" order by oq.createdDate desc" );
//		Query query = this.getEntityManager().createNativeQuery(sql.toString()).setParameter("corpId", corpId);
//		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//		query.setFirstResult(start);
//	    query.setMaxResults(pageSizeInt);
		Map paramMap = new HashMap();
		paramMap.put("corpId", corpId);
		List<Map> r = super.findByListNativeQuery(sql.toString(), "",paramMap,start,pageSizeInt);
		return r;
	}

	/**
	 * 查询
	 * @param id
	 * @return
	 */
	public Map getQuesInfoById(String id) {
		String sql ="SELECT oq.id, oq.name, oq.type as type,oq.createdDate, oq.start_date AS startDate, oq.end_date AS endDate, oq.title_description AS titleDescription, oq.title_description_txt AS titleDescriptionTxt,oq.title as title,oq.publish,s.user_name as createdByName,oq.title_setting as titleSetting FROM oa_questionnaire oq left join sys_user s on s.id=oq.createdBy  WHERE oq.id = :id";
		Map paramMap = new HashMap();
		paramMap.put("id", id);
		List<Map> list = super.findByListNativeQuery(sql, "",paramMap);
		if(CollectionUtils.isNotEmpty(list)) return list.get(0);
		return new HashMap();
	}

	/**
	 * 根据问卷id，查询选择的人或部门
	 * @param quesId
	 * @return
	 */
	public List<Map> getQuesScope(String quesId){
		String sql = " SELECT oqs.scopeType,oqs.scopeValue FROM oa_questionnaire oq INNER JOIN oa_questionnaire_scope oqs " +
				" ON oqs.fieldDataValue = oq.questionnaire_scope" +
				" WHERE oq.id = :id";
		Map paramMap = new HashMap();
		paramMap.put("id", quesId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
		return list;
	}

	/**
	 * 根据fieldDataValue和fieldData，查询name
	 * @param fieldDataValue
	 * @param fieldData
	 * @return
	 */
	public String getscopeName(String fieldDataTable, String fieldDataValue, String fieldData) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select name from oa_questionnaire_scope where fieldDataTable=:fieldDataTable and fieldDataValue=:fieldDataValue and fieldData=:fieldData order by name desc");
		paramMap.put("fieldDataTable", fieldDataTable);
		paramMap.put("fieldDataValue", fieldDataValue);
		paramMap.put("fieldData", fieldData);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
		String result = "";
		if(CollectionUtils.isNotEmpty(list)) {
			for(int i = 0; i < list.size(); i++) {
				if(i == list.size() - 1) result += list.get(i).get("name");
				else result += list.get(i).get("name") + ",";
			}
		}
		return result;
	}


	/**
	 * 设置问卷  已发送
	 * @param quesId
	 */
	public void setQuesSendY(String quesId){
		questionnaireDao.updateSendStatus(quesId,Questionnaire.SendStatusEnum.SEND.getCode());
	}

	/**
	 * 设置问卷  未发送
	 * @param quesId
	 */
	public void setQuesSendN(String quesId){
		questionnaireDao.updateSendStatus(quesId,Questionnaire.SendStatusEnum.NOSEND.getCode());
	}

	/**
	 * 查询所有开启和未开启的问卷
	 * @return
	 */
	public List<Questionnaire> getQuesNoClose(){
		return questionnaireDao.getQuesNoClose();
	}

	/**
	 * 根据id修改问卷发布状态
	 * @param id
	 * @param type
	 * @return
	 */
	public int updateQuesPublish(String id,int type){
		return questionnaireDao.updateQuPublish(id,type);
	}
	
	/**
	 * 根据id修改问卷定时发布状态
	 * 
	 * @param id
	 * @param type
	 * @param isTimingPublish
	 * @param date
	 * @return
	 */
	public int updateQuTimingPublish(String id, int type, int isTimingPublish, Date date) {
		return questionnaireDao.updateQuTimingPublish(id, type, isTimingPublish, date);
	}
	
	/**
	 * 根据id停止问卷定时发布状态
	 * 
	 * @param id
	 * @param type
	 * @param isTimingPublish
	 * @return
	 */
	public int stopQuTimingPublish(String id, int type, int isTimingPublish) {
		return questionnaireDao.stopQuTimingPublish(id, type, isTimingPublish);
	}

	/**
	 * 更新问卷设计入口
	 * @param id
	 * @param isMobile
	 * @return
	 */
	public int updateQuesMobile(String id,String topicJson,String isMobile){
		return questionnaireDao.updateMobile(id,topicJson,isMobile);
	}


	/**
	 * 根据id查找问卷信息
	 * @param id
	 * @return
	 */
	public Map<String,Object> getQuesById(String id){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select oq.id,oq.name,su.user_name,oq.type,oq.status,oq.end_date endDate, ");
		sql.append(" oq.questionnaire_scope questionnaireScope,oq.answer_scope answerScope,oq.description,oq.close_date,oq.is_timing_publish isTimingPublish,oq.publish_date,oq.remind_target ");
		sql.append(" from oa_questionnaire oq left join sys_user su on su.id = oq.createdBy ");
		sql.append(" where oq.id = :id");
		paramMap.put("id", id);
		List<Map> list = super.findByListNativeQuery(sql.toString(), null,paramMap);
		if(CollectionUtils.isNotEmpty(list)){
			return list.get(0);
		}
		return new HashMap<String,Object>();
	}


	/**
	 * 查询统计列表
	 * @param isSuperAdmin  是否是超级管理员
	 * @param publish   发布状态
	 * @param userId
	 * @param corpId
	 * @param token
	 * @param pageable
	 * @param buildFilters
	 * @return
	 */
	public Page<Map> getStaticList(boolean isSuperAdmin,String publish, String userId, String corpId, String token, Pageable pageable,List<PropertyFilter> buildFilters){
		
		List<Map> userL=this.findByListNativeQuery("select user_status as userStatus,is_delete as isDelete from sys_user where id='"+userId+"'", "");
		if(userL!=null && userL.size()>0) {
			Map userStatus=userL.get(0);
			if("offDuty".equals(userStatus.get("userStatus"))||"1".equals(userStatus.get("isDelete")+"")) {
				return new PageImpl<>(new ArrayList<>());
			}
		}
		String sql ="select oq.id,oq.createdBy,oq.name,oq.type,oq.start_date as startdate,oq.end_date as enddate,fn_date_format(oq.close_date,'yyyy-MM-dd HH:mm') as closeDate,"
				+ " oq.status,oqas.count as count ,oq.publish,oq.createdDate,oq.all_user_num as allUserNum "
				+ " from oa_questionnaire oq LEFT JOIN (select count(*) as count ,questionnaire_id from oa_qusetionnaire_answer_status where status in ('1','4') group by questionnaire_id)oqas ON oqas.questionnaire_id = oq.ID  where oq.corp_id = :corpId";
		if(StringUtils.isNotBlank(publish)){
			sql += " and oq.publish = '" + publish + "' ";
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("corpId", corpId);
		if(!isSuperAdmin){
			String scopeSql = this.cmpApplyScopeService.getInScopeDataSql(userId, "oa_questionnaire_scope", "oa_questionnaire", "answer_scope", "oq", paramMap);
			List<String> list = this.cmpApplyScopeService.getAllOrgStaGrpIdsByUserId(userId);
			paramMap.put("OrgStaGrpIds", list);
			sql += " and " + scopeSql;
		}
		sql = PropertyFilter.getSqlByFilterAndPageable("oq",sql,"oq.createdDate desc", buildFilters,pageable);
		Page<Map> page = this.findByPageNativeSQL(pageable, sql,paramMap);
		return page;
	}


	/**
	 * 手机端分页查找问卷统计
	 * @param startDate 查询创建时间，开始时间   yyyy-mm-dd
	 * @param endDate   查询创建时间，结束时间
	 * @param quesType  问卷状态，调查、投票
	 * @param publish    问卷发布状态
	 * @param search    问卷名称查找
	 * @param page     	页码
	 * @param pageSize  一页显示数
	 * @param userId
	 * @param corpId
	 * @param token
	 * @return
	 */
	public List<Map> getStaticList2Mobile(String startDate,String endDate,String quesType,String publish,String search,String page,String pageSize,String userId,String corpId,String token){
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		Map<String,Object> paramMap = new HashMap<>();
		StringBuffer sql = new StringBuffer();
		sql.append("select oq.id,oq.name,oq.type,oq.start_date as startdate,oq.end_date as enddate,"
				+ " oq.status,oqas.count as count ,oq.publish,oq.createdDate "
				+ " from oa_questionnaire oq LEFT JOIN (select count(*) as count ,questionnaire_id from "
				+ " oa_qusetionnaire_answer_status where status in ('1','4')"
				+ " group by questionnaire_id)"
				+ " oqas ON oqas.questionnaire_id = oq.ID  where oq.corp_id = :corpId ");
		paramMap.put("corpId",corpId);
		List<String> userList = orgApiService.getOrgIdsByUserIds(userId,corpId,"","2",token);
		userList.add(userId);
		List<String> list = popScopeService.getFieldDataValue("oa_questionnaire_scope", userList, "oa_questionnaire", "answer_scope");
		if(list == null || list.size()==0){
			sql.append(" and 1=2 ");
		}else{
			sql.append(" and oq.answer_scope in (:list)");
			paramMap.put("list", list);
		}
		if(StringUtils.isNotBlank(startDate)){
			sql.append(" and fn_date_format(oq.createdDate,'yyyy-MM-dd') >= '" + startDate + "'");
		}
		if(StringUtils.isNotBlank(endDate)){
			sql.append(" and fn_date_format(oq.createdDate,'yyyy-MM-dd') <= '" + endDate + "'");
		}
		if(StringUtils.isNotBlank(quesType)){
			sql.append(" and oq.type = '"+quesType + "'");
		}
		if(StringUtils.isNotBlank(publish)){
			sql.append(" and oq.publish = " + publish);
		}
		if(StringUtils.isNotBlank(search)){
			search = search.replaceAll("_","\\\\_");
			sql.append(" and oq.name like '%" + search + "%'" );
		}
		List<Map> listMap = super.findByListNativeQuery(sql.toString()," oq.createdDate desc ",paramMap,start,pageSizeInt);
		return listMap;
	}
	
	/**
	 * 未答卷统计列表
	 * @param pageable 系统参数：分页参数
	 * @param propertyFilter 系统参数：页面参数，如：搜索字段
	 * @param questionnaireId 问卷ID
	 * @param topicId 搜索字段
	 * @return 答案详情列表分页数据
	 */
	public Page<Map> answerDetailList(Pageable pageable,List<PropertyFilter> propertyFilter,String questionnaireId, String topicId ){
		String corpId =WebUtils.getCurrentUser().getCorpId();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("questionnaireId", questionnaireId);
		paramMap.put("topicId", topicId);
		String sql ="select distinct su.id,su.user_name  from oa_questionnaire_answer oqa  " + 
				"LEFT JOIN sys_user su " + 
				"on oqa.user_id = su.id " + 
				"where oqa.questionnaire_id =:questionnaireId  " + 
				"and oqa.topic_id =:topicId  ";
		Page<Map> page = this.findByPageNativeSQL(pageable, sql,paramMap);
		return page;
	}
	
	public List<Map> getAllUser(String corpId) {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select su.id,su.user_name as userName,so.org_name as orgName from sys_user su");
		sql.append(" left join sys_org_user sou on sou.user_id = su.id");
		sql.append(" left join sys_org so on so.id = sou.org_id where");
		sql.append(" su.is_delete=0 and su.user_status!='offDuty' and su.corp_id=:corpId ");
		sql.append(" and sou.isMain = 1 order by su.user_name");
		paramMap.put("corpId", corpId);
		return super.findByListNativeQuery(sql.toString(), null, paramMap);
	}
	
	/**
	 * 根据json字符串 获取所有用户数
	 * @param jsonStr [{'scopeType':'user','scopeValue':'81081a2360254c73a018de8985af8240','scopeName':'徐瑞星'},
    	  				{'scopeType':'org','scopeValue':'40289a3e650e47d301650e585f2e0001','scopeName':'万户','orgType':'3'},
    	  				{'scopeType':'user','scopeValue':'4028803a691296eb0169141ff1fd0095','scopeName':'王凯成'}]
	 * @return
	 */
	public Set<String> getAllUserNum(String jsonStr,String corpId,String token) {
		if (!ValidateUtils.validateChar(jsonStr, "%+")) {
			return new TreeSet<String>();
		}

		if ("".equals(jsonStr)) {
		    return new TreeSet<String>();
		}
		
		//解析json字符串
		List listJson = JSON.parseArray(jsonStr);
	    List<String> listUser = new ArrayList();
	    List<String> listOrgUser = new ArrayList();
	    List<String> orgUserIdList = new ArrayList();
	    
	    String scopeType = "";
	    String scopeValue = "";
	    Map mapJson = new HashMap();
	    for (int i = 0; i < listJson.size(); i++) {
	    	mapJson = (Map)listJson.get(i);
	    	scopeType = mapJson.get("scopeType")==null?"":mapJson.get("scopeType")+"";
	    	scopeValue = mapJson.get("scopeValue")==null?"":mapJson.get("scopeValue")+"";
	    	if("user".equals(scopeType)) {//用户
	    	  	listUser.add(scopeValue);
	    	}
	    	if("org".equals(scopeType)) {//组织
	    		List<String> userIdList = userApiService.getUserIdsByOrgId(scopeValue, "", "1", corpId, token);
	    		orgUserIdList.addAll(userIdList);
	    	}
	    }
	    Set<String> test = new TreeSet<>();
	    if(orgUserIdList!=null && orgUserIdList.size()>0) {
			for(String userId : orgUserIdList) {
				test.add(userId);
			}
		}
	    if(listUser!=null && listUser.size()>0) {
	    	for(String userId : listUser) {
				test.add(userId);
			}
  	  	}
		return test;
	}

    /**
     * 每日定时任务：更新超期问卷信息
     * @param corpId 
     */
	public void updateOverdueQuestionnaire() {
		int s = questionnaireDao.updateOverdueQuestionnaire(new Date());
        LOGGER.info("更新超期问卷：" + s + "条");
	}
	
	/**
	 * 每日定时任务：定时发布问卷
	 */
	public int publishQuestionnaire(List<String> idList) {
		int s = questionnaireDao.publishQuestionnaire(idList);
        LOGGER.info("定时发布问卷：" + s + "条");
        return s;
	}
	
	/**
	 * 查询所有待定时发布的问卷
	 * 
	 * @param date
	 * @return List<Questionnaire>
	 */
	public List<Questionnaire> getPublishQuestionnaire(Date date) {
		return this.questionnaireDao.getPublishQuestionnaire(date);
	}
	
	//是否能重新答题
	public boolean canToAnswer(Map info){
		if(("1".equals(info.get("answerStatus"))||"4".equals(info.get("answerStatus"))||info.get("answerStatus")==null) && "questionnaireExam".equals(info.get("type"))){
			//如果答题成绩或者答题数量为空则表示第一次答题允许答题
			if(info.get("grade")==null||info.get("answerNum")==null) {
				return true;
			}
			//如果考试设置了不限制次数，只要总分低于考试设置总分或者未设置考试总分则允许答题
			if(("1".equals(info.get("noLimitSet")) && (StringUtils.isNotBlank((String)info.get("passScore"))?Float.valueOf(String.valueOf(info.get("grade")))<Float.valueOf((String)info.get("passScore")):true)) 
					//如果考试设置限制了次数，只要总次数在设置的限制范围之内，并且总分低于考试设置的总分或者未设置考试总分则允许答题
					||("0".equals(info.get("noLimitSet")) && (StringUtils.isNotBlank((String)info.get("passScore"))?Float.valueOf(String.valueOf(info.get("grade")))<Float.valueOf((String)info.get("passScore")):true) && Integer.valueOf(String.valueOf(info.get("answerNum")))<Integer.valueOf((String)info.get("answerNumSet")))
					//如果考试没有设置限制次数，和不限制次数，只要总分低于考试设置的总分则允许答题,未设置考试总分不允许再次答题
					||(!"1".equals(info.get("noLimitSet")) && !"0".equals(info.get("noLimitSet")) && (
							StringUtils.isNotBlank((String)info.get("passScore"))?Float.valueOf(String.valueOf(info.get("grade")))<Float.valueOf((String)info.get("passScore")):false))){
				return  true;
			}
		}
		return  false;
	}
	
	public boolean canToAnswer(QusetionnaireAnswerStatus status,Questionnaire ques){
		if(("1".equals(status.getStatus())||"4".equals(status.getStatus())) && "questionnaireExam".equals(ques.getType())){
			if(("1".equals(ques.getNoLimit()) && (StringUtils.isNotBlank(ques.getPassScore())?status.getGrade()<Float.valueOf(ques.getPassScore()):true)) 
					||("0".equals(ques.getNoLimit()) && (StringUtils.isNotBlank(ques.getPassScore())?status.getGrade()<Float.valueOf(ques.getPassScore()):true) && status.getAnswerNum()<Integer.valueOf(ques.getAnswerNum()))
					||(!"1".equals(ques.getNoLimit()) && !"0".equals(ques.getNoLimit()) && (
							StringUtils.isNotBlank(ques.getPassScore())?status.getGrade()<Float.valueOf(ques.getPassScore()):false))){
				return  true;
			}
		}
		return  false;
	}
}
